import { ElMessage } from "element-plus";

/**
 * @description: 初始化websocket
 * 断线重连
 */
export function initWebSocket() {
  const clientName = localStorage.getItem("wsName");
  console.log("clientName", clientName);
  if (clientName) {
    const url = `ws://127.0.0.1:8080/${clientName}`;
    const ws = new WebSocket(url);

    ws.onopen = () => {
      console.log("WebSocket 连接成功");
      localStorage.setItem("wsStatus", JSON.stringify(true));
    };

    ws.onerror = (error) => {
      console.error("WebSocket 连接错误:", error);
    };

    ws.onmessage = (event) => {
      console.log("消息进入", JSON.parse(event.data));
      handleMessage(event.data);
    };
  }
}

// 处理消息
function handleMessage(event) {
  const message = JSON.parse(event);

  if (message.status === "connected") {
    ElMessage({
      message: `${message.name} 上线了`,
      type: "success",
    });
  } else if (message.status === "already_connected") {
    ElMessage({
      message: `${message.name}已经存在`,
      type: "warning",
    });
  } else {
    ElMessage({
      message: `${message.name}已经下线`,
      type: "warning",
    });
  }
}
